<template>
  <view class="container">
    <view class="query-counter" v-if="userInfo">
      <text class="counter-icon">🎯</text>
      <text class="counter-text">剩余查询次数：{{ userInfo.remaining_queries }}</text>
      <text class="share-tip">分享给好友，每次被点击可获得5次查询机会~</text>
    </view>
    <view class="result-card" v-for="(nameItem, index) in result.names" :key="index">
      <view class="name-section">
        <text class="title">AI为您推荐的名字</text>
        <text class="name">{{ nameItem.name }}</text>
        <text class="pinyin" v-if="nameItem.pinyin">{{ nameItem.pinyin }}</text>
      </view>

      <view class="divider"></view>

      <view class="detail-section">
        <view class="detail-item" v-for="(content, key) in nameItem.details" :key="key">
          <text class="detail-title">{{ key }}</text>
          <text class="detail-content">{{ content }}</text>
        </view>
      </view>
    </view>

    <view class="action-buttons">
      <button class="action-btn" @click="goBack" :disabled="isGenerating">返回</button>
      <button class="action-btn primary" @click="regenerate" :disabled="isGenerating">重新生成</button>
      <button class="action-btn share" open-type="share">分享</button>
    </view>
  </view>
</template>

<script>
import { generateName } from '@/api/naming.js';
import { getUserInfo } from '@/api/user.js';

export default {
  data() {
    return {
      result: { names: [] },
      isGenerating: false,
      userInfo: null
    };
  },
  mounted() {
    this.getStoredResult();
    this.getUserInfo();
  },
  methods: {
    async getUserInfo() {
      // 无论是否有本地缓存，都重新获取最新的用户信息
      const res = await getUserInfo();
      if (res.data) {
        this.userInfo = res.data;
      }
    },
    parseResponse(response) {
      if (!response || !response.data) {
        uni.showToast({
          title: '未获取到有效数据',
          icon: 'none'
        });
        return { names: [] };
      }

      try {
        const jsonData = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
        
        if (!jsonData.name || !jsonData.meaning) {
          throw new Error('返回数据格式不正确');
        }

        const nameData = {
          name: jsonData.name,
          details: {
            '寓意': jsonData.meaning
          }
        };

        if (jsonData.source) {
          nameData.details['诗词出处'] = jsonData.source;
        }
        if (jsonData.five_elements) {
          nameData.details['五行属性'] = jsonData.five_elements;
        }
        if (jsonData.pinyin) {
          nameData.pinyin = jsonData.pinyin;
        }

        return { names: [nameData] };
      } catch (error) {
        console.error('数据解析失败:', error);
        uni.showToast({
          title: '数据解析失败，请重试',
          icon: 'none'
        });
        return { names: [] };
      }
    },

    getStoredResult() {
      try {
        const storedResult = uni.getStorageSync('naming_result');
        if (storedResult) {
          if (storedResult.names && Array.isArray(storedResult.names)) {
            this.result = storedResult;
          } else {
            const parsedResult = this.parseResponse(storedResult);
            this.result = parsedResult;
          }
        }
      } catch (error) {
        console.error('获取存储数据失败:', error);
      }
    },

    async regenerate() {
      if (this.isGenerating) return;

      try {
        this.isGenerating = true;
        uni.showLoading({
          title: '正在生成...',
          mask: true
        });

        const formData = uni.getStorageSync('naming_form_data');
        if (!formData) {
          throw new Error('未找到表单数据');
        }

        const response = await generateName(formData);
        const parsedResult = this.parseResponse(response);
        this.result = parsedResult;
        
        uni.setStorageSync('naming_result', parsedResult);
        this.getUserInfo()
      } catch (error) {
        console.error('生成名字失败:', error);
        uni.showToast({
          title: error.message || '生成失败，请重试',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
        this.isGenerating = false;
      }
    },

    goBack() {
      uni.navigateBack();
    }
  },

  onShareAppMessage() {
    const path = this.userInfo
      ? `/pages/index/index?sharer_id=${this.userInfo.user_id}`
      : "/pages/index/index";
    return {
      title: "快来给宝宝起个好名字吧",
      path: path,
      success: () => {},
    };
  },
};
</script>

<style lang="less" scoped>
.container {
  padding: 30rpx;
  min-height: 100vh;
  background: #f8f8f8;
}

.query-counter {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  margin-bottom: 30rpx;
  padding: 16rpx;
  background: #f0f7ff;
  border-radius: 8rpx;
  
  .counter-icon {
    font-size: 32rpx;
  }
  
  .counter-text {
    font-size: 28rpx;
    color: #1677ff;
  }

  .share-tip {
    font-size: 24rpx;
    color: #666;
    margin-top: 4rpx;
  }
}

.result-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 30rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.name-section {
  text-align: center;
  margin-bottom: 40rpx;

  .title {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 20rpx;
    display: block;
  }

  .name {
    font-size: 64rpx;
    color: #1677ff;
    font-weight: bold;
    margin-bottom: 16rpx;
    display: block;
  }

  .pinyin {
    font-size: 28rpx;
    color: #999;
  }
}

.divider {
  height: 1rpx;
  background: #f0f0f0;
  margin: 40rpx 0;
}

.detail-section {
  .detail-item {
    margin-bottom: 30rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .detail-title {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 12rpx;
    display: block;
  }

  .detail-content {
    font-size: 30rpx;
    color: #333;
    line-height: 1.6;
  }
}

.action-buttons {
  margin-top: 60rpx;
  display: flex;
  gap: 30rpx;
  flex-wrap: wrap;

  .action-btn {
    flex: 1;
    min-width: 200rpx;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 8rpx;
    font-size: 32rpx;
    background: #fff;
    color: #1677ff;
    border: 2rpx solid #1677ff;

    &.primary {
      background: #1677ff;
      color: #fff;
    }

    &.share {
      background: #07c160;
      color: #fff;
      border-color: #07c160;
    }

    &:active {
      opacity: 0.9;
    }
    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
}
</style>